<template>
  <div class="real-time-analysis">
    <!-- 作业管理 -->
    <el-card class="box-card" style="margin-bottom: 20px;">
      <div slot="header" class="clearfix">
        <span>流任务管理</span>
        <el-button type="primary" size="small" style="float: right;" @click="showCreateTask = true">新建流任务</el-button>
      </div>
      <el-table :data="taskList" style="width: 100%;" size="small">
        <el-table-column prop="name" label="任务名称" width="180"/>
        <el-table-column prop="source" label="数据源" width="180"/>
        <el-table-column prop="parallelism" label="并行度" width="100"/>
        <el-table-column prop="interval" label="检查点间隔" width="120"/>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '运行中' ? 'success' : 'info'" size="mini">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180"/>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="editTask(scope.row)"><i class="el-icon-edit"></i></el-button>
            <el-button type="text" size="mini" @click="deleteTask(scope.row.id)"><i class="el-icon-delete"></i></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新建/编辑流任务弹窗 -->
    <el-dialog :title="editTaskId ? '编辑流任务' : '新建流任务'" :visible.sync="showCreateTask" width="500px" @close="resetTaskForm">
      <el-form :model="taskForm" label-width="120px" :rules="taskRules" ref="taskForm">
        <el-form-item label="数据源" prop="source">
          <el-select v-model="taskForm.source" placeholder="请选择Kafka主题">
            <el-option v-for="item in kafkaTopics" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="并行度" prop="parallelism">
          <el-input-number v-model="taskForm.parallelism" :min="1" :max="32"/>
        </el-form-item>
        <el-form-item label="检查点间隔" prop="interval">
          <el-select v-model="taskForm.interval">
            <el-option label="5分钟" value="5分钟"/>
            <el-option label="10分钟" value="10分钟"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showCreateTask = false">取 消</el-button>
        <el-button type="primary" @click="submitTaskForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- CEP规则配置 -->
    <el-card class="box-card" style="margin-bottom: 20px;">
      <div slot="header" class="clearfix">
        <span>CEP规则配置</span>
        <el-button type="primary" size="small" style="float: right;" @click="showCreateRule = true">添加规则</el-button>
      </div>
      <el-table :data="cepRules" style="width: 100%;" size="small">
        <el-table-column prop="name" label="规则名称" width="180"/>
        <el-table-column prop="condition" label="触发条件"/>
        <el-table-column prop="action" label="动作" width="180"/>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '启用' ? 'success' : 'info'" size="mini">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="editRule(scope.row)"><i class="el-icon-edit"></i></el-button>
            <el-button type="text" size="mini" @click="deleteRule(scope.row.id)"><i class="el-icon-delete"></i></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新建/编辑CEP规则弹窗 -->
    <el-dialog :title="editRuleId ? '编辑规则' : '添加规则'" :visible.sync="showCreateRule" width="500px" @close="resetRuleForm">
      <el-form :model="ruleForm" label-width="120px" :rules="ruleRules" ref="ruleForm">
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称"/>
        </el-form-item>
        <el-form-item label="触发条件" prop="condition">
          <el-input v-model="ruleForm.condition" placeholder="如：振动幅值>80g且温度>120℃持续10秒"/>
        </el-form-item>
        <el-form-item label="动作" prop="action">
          <el-select v-model="ruleForm.action">
            <el-option label="短信通知设备管理员" value="短信通知设备管理员"/>
            <el-option label="邮件通知" value="邮件通知"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="ruleForm.status" active-text="启用" inactive-text="禁用" :active-value="'启用'" :inactive-value="'禁用'"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showCreateRule = false">取 消</el-button>
        <el-button type="primary" @click="submitRuleForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 实时监控看板 -->
    <el-card class="box-card" style="margin-bottom: 20px;">
      <div slot="header" class="clearfix">
        <span>实时监控看板</span>
        <el-button type="primary" size="small" style="float: right;" @click="showPerfDialog = true">动态调整并发数</el-button>
      </div>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="metric-block">
            <div class="metric-label">数据流吞吐量</div>
            <div class="metric-value">{{ metrics.throughput }} <span class="metric-unit">MB/s</span></div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="metric-block">
            <div class="metric-label">平均延迟</div>
            <div class="metric-value">{{ metrics.latency }} <span class="metric-unit">ms</span></div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="metric-block">
            <div class="metric-label">主轴转速均值</div>
            <div class="metric-value">{{ metrics.avgRpm }} <span class="metric-unit">rpm</span></div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="metric-block">
            <div class="metric-label">预警次数</div>
            <div class="metric-value">{{ metrics.alertCount }}</div>
          </div>
        </el-col>
      </el-row>
      <div ref="chart" style="width: 100%; height: 320px; margin-top: 24px;"></div>
    </el-card>

    <!-- 动态调整并发数弹窗 -->
    <el-dialog title="动态调整任务并发数" :visible.sync="showPerfDialog" width="400px">
      <el-form label-width="120px">
        <el-form-item label="当前并发数">
          <el-input-number v-model="metrics.parallelism" :min="1" :max="32"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showPerfDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateParallelism">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 预警通知弹窗 -->
    <el-dialog title="短信预警" :visible.sync="showAlertDialog" width="400px" :show-close="false">
      <div style="text-align:center; font-size:16px; padding: 30px 0;">
        <i class="el-icon-message" style="font-size: 40px; color: #F56C6C; margin-bottom: 10px;"></i>
        <div style="margin-top: 10px;">已触发短信预警，已通知设备管理员！</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showAlertDialog = false">我知道了</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Message, MessageBox } from 'element-ui'
import * as echarts from 'echarts'

const TASKS_KEY = 'realtime_analysis_tasks'
const RULES_KEY = 'realtime_analysis_rules'
const METRICS_KEY = 'realtime_analysis_metrics'
const INFLUX_KEY = 'realtime_analysis_influx'

export default {
  name: 'RealTimeDataAnalysis',
  data() {
    return {
      // 作业管理
      taskList: [],
      showCreateTask: false,
      editTaskId: null,
      taskForm: {
        name: '',
        source: 'vibration_topic',
        parallelism: 8,
        interval: '5分钟',
        status: '运行中',
        createdAt: ''
      },
      taskRules: {
        source: [{ required: true, message: '请选择数据源', trigger: 'change' }],
        parallelism: [{ type: 'number', required: true, min: 1, message: '并行度至少为1', trigger: 'change' }],
        interval: [{ required: true, message: '请选择检查点间隔', trigger: 'change' }]
      },
      kafkaTopics: [
        { label: '设备振动主题', value: 'vibration_topic' },
        { label: '温度监测主题', value: 'temperature_topic' },
        { label: '压力传感器主题', value: 'pressure_topic' }
      ],
      // CEP规则
      cepRules: [],
      showCreateRule: false,
      editRuleId: null,
      ruleForm: {
        name: '',
        condition: '',
        action: '短信通知设备管理员',
        status: '启用'
      },
      ruleRules: {
        name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        condition: [{ required: true, message: '请输入触发条件', trigger: 'blur' }],
        action: [{ required: true, message: '请选择动作', trigger: 'change' }]
      },
      // 实时监控
      metrics: {
        throughput: 12.3,
        latency: 24,
        avgRpm: 1450,
        alertCount: 0,
        parallelism: 8
      },
      chartData: {
        time: [],
        throughput: [],
        latency: [],
        rpm: []
      },
      showPerfDialog: false,
      showAlertDialog: false,
      influxData: []
    }
  },
  mounted() {
    this.loadTasks()
    this.loadRules()
    this.loadMetrics()
    this.loadInflux()
    this.initChart()
    this.startMockStream()
  },
  beforeDestroy() {
    clearInterval(this.mockTimer)
  },
  methods: {
    // 作业管理
    loadTasks() {
      const tasks = JSON.parse(localStorage.getItem(TASKS_KEY) || '[]')
      this.taskList = tasks
    },
    saveTasks() {
      localStorage.setItem(TASKS_KEY, JSON.stringify(this.taskList))
    },
    resetTaskForm() {
      this.editTaskId = null
      this.taskForm = {
        name: '',
        source: 'vibration_topic',
        parallelism: 8,
        interval: '5分钟',
        status: '运行中',
        createdAt: ''
      }
      if (this.$refs.taskForm) this.$refs.taskForm.resetFields()
    },
    submitTaskForm() {
      this.$refs.taskForm.validate(valid => {
        if (!valid) return
        const newTask = {
          id: this.editTaskId || Date.now(),
          name: this.taskForm.source === 'vibration_topic' ? '设备振动监控' : (this.taskForm.source === 'temperature_topic' ? '温度异常检测' : '压力传感器数据处理'),
          source: this.taskForm.source,
          parallelism: this.taskForm.parallelism,
          interval: this.taskForm.interval,
          status: '运行中',
          createdAt: this.editTaskId
            ? this.taskList.find(t => t.id === this.editTaskId).createdAt
            : this.formatDate(new Date())
        }
        if (this.editTaskId) {
          const idx = this.taskList.findIndex(t => t.id === this.editTaskId)
          this.$set(this.taskList, idx, newTask)
        } else {
          this.taskList.push(newTask)
        }
        this.saveTasks()
        this.showCreateTask = false
        this.resetTaskForm()
        Message.success('任务保存成功')
      })
    },
    editTask(row) {
      this.editTaskId = row.id
      this.taskForm = {
        name: row.name,
        source: row.source,
        parallelism: row.parallelism,
        interval: row.interval,
        status: row.status,
        createdAt: row.createdAt
      }
      this.showCreateTask = true
    },
    deleteTask(id) {
      MessageBox.confirm('确定要删除该任务吗？', '提示', { type: 'warning' })
        .then(() => {
          this.taskList = this.taskList.filter(t => t.id !== id)
          this.saveTasks()
          Message.success('删除成功')
        })
        .catch(() => {})
    },
    // CEP规则
    loadRules() {
      const rules = JSON.parse(localStorage.getItem(RULES_KEY) || '[]')
      this.cepRules = rules
    },
    saveRules() {
      localStorage.setItem(RULES_KEY, JSON.stringify(this.cepRules))
    },
    resetRuleForm() {
      this.editRuleId = null
      this.ruleForm = {
        name: '',
        condition: '',
        action: '短信通知设备管理员',
        status: '启用'
      }
      if (this.$refs.ruleForm) this.$refs.ruleForm.resetFields()
    },
    submitRuleForm() {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return
        const newRule = {
          id: this.editRuleId || Date.now(),
          name: this.ruleForm.name,
          condition: this.ruleForm.condition,
          action: this.ruleForm.action,
          status: this.ruleForm.status
        }
        if (this.editRuleId) {
          const idx = this.cepRules.findIndex(r => r.id === this.editRuleId)
          this.$set(this.cepRules, idx, newRule)
        } else {
          this.cepRules.push(newRule)
        }
        this.saveRules()
        this.showCreateRule = false
        this.resetRuleForm()
        Message.success('规则保存成功')
      })
    },
    editRule(row) {
      this.editRuleId = row.id
      this.ruleForm = {
        name: row.name,
        condition: row.condition,
        action: row.action,
        status: row.status
      }
      this.showCreateRule = true
    },
    deleteRule(id) {
      MessageBox.confirm('确定要删除该规则吗？', '提示', { type: 'warning' })
        .then(() => {
          this.cepRules = this.cepRules.filter(r => r.id !== id)
          this.saveRules()
          Message.success('删除成功')
        })
        .catch(() => {})
    },
    // 实时监控
    loadMetrics() {
      const metrics = JSON.parse(localStorage.getItem(METRICS_KEY) || 'null')
      if (metrics) {
        this.metrics = metrics
      }
    },
    saveMetrics() {
      localStorage.setItem(METRICS_KEY, JSON.stringify(this.metrics))
    },
    loadInflux() {
      const influx = JSON.parse(localStorage.getItem(INFLUX_KEY) || '[]')
      this.influxData = influx
    },
    saveInflux() {
      localStorage.setItem(INFLUX_KEY, JSON.stringify(this.influxData))
    },
    formatDate(date) {
      const d = new Date(date)
      return `${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2,'0')}-${d.getDate().toString().padStart(2,'0')} ${d.getHours().toString().padStart(2,'0')}:${d.getMinutes().toString().padStart(2,'0')}`
    },
    // 模拟Kafka流和窗口聚合、CEP规则检测
    startMockStream() {
      // 初始化图表数据
      const now = new Date()
      this.chartData.time = []
      this.chartData.throughput = []
      this.chartData.latency = []
      this.chartData.rpm = []
      for (let i = 0; i < 20; i++) {
        const t = new Date(now.getTime() - (19 - i) * 60000)
        this.chartData.time.push(t.getHours().toString().padStart(2, '0') + ':' + t.getMinutes().toString().padStart(2, '0'))
        this.chartData.throughput.push(10 + Math.random() * 5)
        this.chartData.latency.push(20 + Math.random() * 20)
        this.chartData.rpm.push(1400 + Math.random() * 200)
      }
      this.updateChart()
      // 定时模拟数据流
      this.mockTimer = setInterval(() => {
        // 模拟Kafka数据
        const throughput = 10 + Math.random() * 5 // MB/s
        const latency = 20 + Math.random() * 30 // ms
        const rpm = 1400 + Math.random() * 200 // 主轴转速
        // 窗口聚合（1分钟）
        this.chartData.time.push(this.getTimeLabel(new Date()))
        this.chartData.throughput.push(throughput)
        this.chartData.latency.push(latency)
        this.chartData.rpm.push(rpm)
        if (this.chartData.time.length > 20) {
          this.chartData.time.shift()
          this.chartData.throughput.shift()
          this.chartData.latency.shift()
          this.chartData.rpm.shift()
        }
        // 计算主轴转速均值
        const avgRpm = Math.round(this.chartData.rpm.reduce((a, b) => a + b, 0) / this.chartData.rpm.length)
        // 更新监控指标
        this.metrics.throughput = throughput.toFixed(1)
        this.metrics.latency = Math.round(latency)
        this.metrics.avgRpm = avgRpm
        // 动态并发数影响吞吐量和延迟
        this.metrics.throughput = (throughput * (this.metrics.parallelism / 8)).toFixed(1)
        this.metrics.latency = Math.max(10, Math.round(latency * (8 / this.metrics.parallelism)))
        // 写入InfluxDB（本地模拟）
        this.influxData.push({
          time: Date.now(),
          rpm: avgRpm,
          throughput: this.metrics.throughput,
          latency: this.metrics.latency
        })
        if (this.influxData.length > 1000) this.influxData.shift()
        this.saveInflux()
        // CEP规则检测（只检测第一个启用的规则）
        const activeRule = this.cepRules.find(r => r.status === '启用')
        if (activeRule && this.checkCepCondition(activeRule.condition, rpm, throughput, latency)) {
          this.metrics.alertCount++
          this.saveMetrics()
          this.showAlertDialog = true
        }
        this.saveMetrics()
        this.updateChart()
      }, 3000)
    },
    getTimeLabel(date) {
      return date.getHours().toString().padStart(2, '0') + ':' + date.getMinutes().toString().padStart(2, '0')
    },
    // 简单解析条件字符串，支持“振动幅值>80g且温度>120℃持续10秒”
    checkCepCondition(cond, rpm, throughput, latency) {
      // 只模拟“振动幅值>80g且温度>120℃持续10秒”
      if (cond.includes('振动幅值>80g') && cond.includes('温度>120')) {
        // 随机概率触发
        return Math.random() < 0.1
      }
      return false
    },
    // 图表
    initChart() {
      this.$nextTick(() => {
        if (!this.$refs.chart) return
        this.chart = echarts.init(this.$refs.chart)
        this.updateChart()
        window.addEventListener('resize', () => this.chart && this.chart.resize())
      })
    },
    updateChart() {
      if (!this.chart) return
      this.chart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: ['吞吐量(MB/s)', '延迟(ms)', '主轴转速(rpm)'] },
        xAxis: { type: 'category', data: this.chartData.time },
        yAxis: [
          { type: 'value', name: '吞吐量', min: 0, max: 20 },
          { type: 'value', name: '延迟', min: 0, max: 100, position: 'right' }
        ],
        series: [
          {
            name: '吞吐量(MB/s)',
            type: 'line',
            data: this.chartData.throughput,
            yAxisIndex: 0,
            smooth: true
          },
          {
            name: '延迟(ms)',
            type: 'line',
            data: this.chartData.latency,
            yAxisIndex: 1,
            smooth: true
          },
          {
            name: '主轴转速(rpm)',
            type: 'bar',
            data: this.chartData.rpm,
            yAxisIndex: 0,
            barWidth: 10,
            itemStyle: { opacity: 0.5 }
          }
        ],
        grid: { top: 40, left: 60, right: 60, bottom: 40 }
      })
    },
    // 动态调整并发数
    updateParallelism() {
      this.showPerfDialog = false
      Message.success('并发数已调整为 ' + this.metrics.parallelism)
    }
  }
}
</script>

<style scoped>
.real-time-analysis {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px 0;
}
.box-card {
  margin-bottom: 24px;
}
.metric-block {
  background: #f7fafd;
  border-radius: 8px;
  padding: 18px 0 10px 0;
  text-align: center;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.03);
}
.metric-label {
  color: #888;
  font-size: 13px;
  margin-bottom: 6px;
}
.metric-value {
  font-size: 26px;
  font-weight: bold;
  color: #409EFF;
}
.metric-unit {
  font-size: 14px;
  color: #888;
  margin-left: 2px;
}
</style>
